package ms.unicorn.reasoning.subcribers;

import java.util.ArrayList;
import java.util.Collection;

import org.eclipse.draw2d.IFigure;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gef.EditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
import org.eclipse.gmf.runtime.notation.View;

import ms.unicorn.Element;
import ms.unicorn.NotificationService.Subscription;
import ms.unicorn.reasoning.UnicornDSL;
import ms.unicorn.reasoning.util.UnicornDSLUtil;
import ms.unicorn.util.FigureUtil;
import ms.unicorn.util.NotificationService;
import ms.unicorn.dsl.ILanguageElement;
import ms.unicorn.dsl.ITheme;
import ms.unicorn.dsl.LanguageRegistry;

public class OriginalModelThemeSelectorSubscriber implements NotificationService.Subscriber<Object, ITheme> {

	public static Collection<Integer> PREFER_CHANNELS = new ArrayList<Integer>(2);
	
	static {
		PREFER_CHANNELS.add(NotificationService.CHANNEL_THEME);
		PREFER_CHANNELS.add(NotificationService.CHANNEL_EDITPART);
	}
	
	public OriginalModelThemeSelectorSubscriber() {		// TODO Auto-generated constructor stub
	}
	
	@Override
	public Collection<Integer> getPreferChannels() {
		return PREFER_CHANNELS;
	}

	@Override
	public int hanldeSubscription(Object sender, int channel,
			Subscription<Object, ITheme> subscription) {
		switch (channel) {
		case NotificationService.CHANNEL_THEME:
			if (subscription.getEvent() == NotificationService.THEME_RESOLVE && sender instanceof IFigure) {
				IFigure figure = (IFigure) sender;
				EditPart editPart = FigureUtil.resolveEditPart(figure);
				if (editPart != null) {
					Element domainElement = (Element) ((View) editPart.getModel()).getElement();
					ILanguageElement element = LanguageRegistry.INSTANCE.getLanguageElement(domainElement);
					if (UnicornDSLUtil.isRequirement(domainElement)) {
						ITheme result = null;
						if (UnicornDSLUtil.isOriginalModelElement(domainElement))
							result = element.getElementProperty("themes.original", null);
						else
							result = element.getElementProperty("themes.evolved", null);
						subscription.setResult(result);
					}
					
				}
			}
			break;
		case NotificationService.CHANNEL_EDITPART:
			if (sender instanceof EditPart && subscription.getData() instanceof Notification) {
				Notification notification = (Notification) subscription.getData();
				Object feature = notification.getFeature();
				if (feature instanceof EAttribute) {
					if (feature.equals(UnicornDSL.ORIGIN_MODEL_ELEMENT)) {
						GraphicalEditPart s = (GraphicalEditPart) sender;
						s.getFigure().repaint();
					}
				}
			}
			break;
		}
		return NotificationService.SUBSCRIPTION_NORMAL;
	}

}
